<?php
namespace app\shouyin\model;

use think\Model;
use app\product\model\Product as ProductModel;
use app\product\model\Project as ProjectModel;

class Course extends Model
{
    protected $field = true;
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    public function hasProject()
    {
        return $this->hasMany('app\product\model\Project', 'id', 'project_ids');
    }

    public function getTypeTextAttr($value)
    {
        $type = [
            1=>'储值卡',
            2=>'疗程卡',
            3=>'产品卡'
        ];
        return $type[$value];
    }

    public function getCourseJsonTextAttr($value, $data)
    {
        $arr = json_decode($data['course_json']);
        if($data['type'] == 1){
            return '充值金额：'.$arr->price1 .'<br>'. '赠送金额：'.$arr->price2;
        }

        if($data['type'] == 2){
            $re = [];
            $str = '';
            foreach ($arr as $key => $value) {
                $name = ProjectModel::where('id', $value->project)->value('name');
                $str .= $name . ' * ' .$value->num.'<br>';
            }
            return $str;
        }

        if($data['type'] == 3){
            $re = [];
            $str = '';
            foreach ($arr as $key => $value) {
                $name = ProductModel::where('id', $value->product)->value('name');
                $str .= $name . ' * ' .$value->num.'<br>';
            }
            return $str;
        }

    }

    /**
     * 将数据集格式化成下拉选项
     * @param int $id 选中的ID
     * @author 橘子俊 <364666827@qq.com>
     * @return string
     */
    public static function getSelect($data = [], $id = 0, $level = 0)
    {
        if (empty($data)) {
            return '';
        }
        $str = $separ = '';
        if ($level > 0) {
            for ($i=0; $i < $level; $i++) {
                $separ .= '&nbsp;&nbsp;&nbsp;';
            }
            $separ .= '┣&nbsp;';
        }

        foreach ($data as $k => $v) {
            if ($id == $v['id']) {
                $str .= '<option value="'.$v['id'].'" selected>'.$separ.$v['name'].'</option>';
            } else {
                $str .= '<option value="'.$v['id'].'">'.$separ.$v['name'].'</option>';
            }
            if (isset($v['childs'])) {
                $str.= self::getSelect($v['childs'], $id, $level+1);
            }
        }
        return $str;
    }
}
